package com.netposa.datawarehouse.statistics.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.netposa.datawarehouse.statistics.config.MachineStateDataConfig;
import com.netposa.datawarehouse.statistics.config.PropertiesConfig;
import com.netposa.datawarehouse.statistics.vo.DeviceStateCountVO;
import com.netposa.datawarehouse.statistics.vo.MachineRunStateVO;
import com.netposa.datawarehouse.statistics.vo.MachineStateVO;
import com.netposa.datawarehouse.statistics.vo.MockMachineState;
import com.netposa.datawarehouse.statistics.vo.MonitorResp;
import com.netposa.datawarehouse.statistics.vo.MonitorVO;
import com.netposa.datawarehouse.statistics.vo.RulesVO;
import com.netposa.npwonder.base.exception.BusinessException;
import com.netposa.npwonder.base.util.FileUtils;
import com.netposa.npwonder.base.util.RestAssert;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MaintenanceService {
   private static final Logger log = LoggerFactory.getLogger(MaintenanceService.class);
   @Autowired
   private PropertiesConfig propertiesConfig;
   @Autowired
   private RestAssert restAssert;
   @Autowired
   private MachineStateDataConfig config;

   public Map deviceState() {
      Map returnVal = Maps.newHashMap();
      DeviceStateCountVO ceamera = new DeviceStateCountVO(2305L, 353L);
      DeviceStateCountVO traffic = new DeviceStateCountVO(2305L, 353L);
      MachineRunStateVO machine = new MachineRunStateVO(102L, 26L, 26L);
      returnVal.put("camera", ceamera);
      returnVal.put("traffic", traffic);
      returnVal.put("machine", machine);
      return returnVal;
   }

   public MachineRunStateVO machineCount() {
      return this.config.getDataMock() ? this.mockMachineCount() : this.realMachineCount();
   }

   private MachineRunStateVO realMachineCount() {
      try {
         MonitorResp monitorData = this.getMonitorData();
         return this.getMachineState(monitorData);
      } catch (Exception var2) {
         log.error(var2.getMessage(), var2);
         return new MachineRunStateVO();
      }
   }

   private MachineRunStateVO mockMachineCount() {
      try {
         String jsonStr = this.readFile();
         JSONArray arrays = JSON.parseArray(jsonStr);
         return new MachineRunStateVO((long)arrays.size(), 0L, 0L);
      } catch (Exception var3) {
         log.error(var3.getMessage(), var3);
         return new MachineRunStateVO();
      }
   }

   private MachineRunStateVO getMachineState(MonitorResp monitorData) {
      List data = monitorData.getData().toJavaList(MonitorVO.class);
      MonitorResp rulesData = this.getRulesData();
      Long normal = 0L;
      Long abnormal = 0L;
      Long warn = 0L;
      if (data != null && !data.isEmpty()) {
         Iterator var7 = data.iterator();

         while(true) {
            while(var7.hasNext()) {
               MonitorVO monitorVO = (MonitorVO)var7.next();
               if (monitorVO.getCPUUsage() == 0.0 && monitorVO.getDiskUsage() == 0.0 && monitorVO.getMemUsage() == 0.0 && monitorVO.getNetworkUsage() == 0.0) {
                  abnormal = abnormal + 1L;
               } else if (this.isWarnState(monitorVO, rulesData)) {
                  warn = warn + 1L;
               } else {
                  normal = normal + 1L;
               }
            }

            return new MachineRunStateVO(normal, abnormal, warn);
         }
      } else {
         return new MachineRunStateVO(normal, abnormal, warn);
      }
   }

   private boolean isWarnState(MonitorVO monitorVO, MonitorResp rulesData) {
      JSONArray data = rulesData.getData();

      for(int i = 0; i < data.size(); ++i) {
         JSONObject json = data.getJSONObject(i);
         if (json.getString("serverIP").equals(monitorVO.getServerIP())) {
            List rules = json.getJSONArray("rules").toJavaList(RulesVO.class);
            Iterator var7 = rules.iterator();

            while(var7.hasNext()) {
               RulesVO rulesVO = (RulesVO)var7.next();
               switch (rulesVO.getThresholdSign()) {
                  case "<":
                     return this.lessthan(rulesVO, monitorVO);
                  case "<=":
                     return this.lessthanEquals(rulesVO, monitorVO);
                  case ">":
                     return this.morethan(rulesVO, monitorVO);
                  case ">=":
                     return this.morethanEquals(rulesVO, monitorVO);
               }
            }
         }
      }

      return false;
   }

   private boolean lessthan(RulesVO rulesVO, MonitorVO monitorVO) {
      Integer warnValue = Integer.valueOf(rulesVO.getThresholdValue());
      switch (rulesVO.getKPIID()) {
         case "2000":
            return monitorVO.getCPUUsage() < (double)warnValue;
         case "2001":
            return monitorVO.getMemUsage() < (double)warnValue;
         case "2002":
            return monitorVO.getDiskUsage() < (double)warnValue;
         case "2003":
            return monitorVO.getNetworkUsage() < (double)warnValue;
         default:
            return false;
      }
   }

   private boolean lessthanEquals(RulesVO rulesVO, MonitorVO monitorVO) {
      Integer warnValue = Integer.valueOf(rulesVO.getThresholdValue());
      switch (rulesVO.getKPIID()) {
         case "2000":
            return monitorVO.getCPUUsage() <= (double)warnValue;
         case "2001":
            return monitorVO.getMemUsage() <= (double)warnValue;
         case "2002":
            return monitorVO.getDiskUsage() <= (double)warnValue;
         case "2003":
            return monitorVO.getNetworkUsage() <= (double)warnValue;
         default:
            return false;
      }
   }

   private boolean morethan(RulesVO rulesVO, MonitorVO monitorVO) {
      Integer warnValue = Integer.valueOf(rulesVO.getThresholdValue());
      switch (rulesVO.getKPIID()) {
         case "2000":
            return monitorVO.getCPUUsage() > (double)warnValue;
         case "2001":
            return monitorVO.getMemUsage() > (double)warnValue;
         case "2002":
            return monitorVO.getDiskUsage() > (double)warnValue;
         case "2003":
            return monitorVO.getNetworkUsage() > (double)warnValue;
         default:
            return false;
      }
   }

   private boolean morethanEquals(RulesVO rulesVO, MonitorVO monitorVO) {
      Integer warnValue = Integer.valueOf(rulesVO.getThresholdValue());
      switch (rulesVO.getKPIID()) {
         case "2000":
            return monitorVO.getCPUUsage() >= (double)warnValue;
         case "2001":
            return monitorVO.getMemUsage() >= (double)warnValue;
         case "2002":
            return monitorVO.getDiskUsage() >= (double)warnValue;
         case "2003":
            return monitorVO.getNetworkUsage() >= (double)warnValue;
         default:
            return false;
      }
   }

   public List machineState() {
      return this.config.getDataMock() ? this.mockMachineState() : this.realMachineState();
   }

   private List realMachineState() {
      List retVal = Lists.newArrayList();

      try {
         MonitorResp monitorData = this.getMonitorData();
         List data = monitorData.getData().toJavaList(MonitorVO.class);
         if (data != null && !data.isEmpty()) {
            Iterator var4 = data.iterator();

            while(var4.hasNext()) {
               MonitorVO monitorVO = (MonitorVO)var4.next();
               retVal.add(new MachineStateVO(monitorVO.getObjName(), monitorVO.getCPUUsage(), monitorVO.getDiskUsage(), monitorVO.getCPUUsage() == 0.0 ? 0.0 : RandomUtils.nextDouble(0.0, 100.0), monitorVO.getMemUsage(), monitorVO.getNetworkUsage(), monitorVO.getNetworkUsage()));
            }
         }
      } catch (Exception var6) {
         log.error(var6.getMessage(), var6);
      }

      return retVal;
   }

   private List mockMachineState() {
      List retVal = Lists.newArrayList();

      try {
         String jsonContext = this.readFile();
         JSONArray jsonArray = JSONArray.parseArray(jsonContext);
         List data = jsonArray.toJavaList(MockMachineState.class);
         if (data != null && !data.isEmpty()) {
            Iterator var5 = data.iterator();

            while(var5.hasNext()) {
               MockMachineState mockData = (MockMachineState)var5.next();
               retVal.add(this.convert(mockData));
            }
         }
      } catch (Exception var7) {
         log.error(var7.getMessage(), var7);
      }

      return retVal;
   }

   private MachineStateVO convert(MockMachineState mockMachineState) {
      String name = "";
      Double cpu = 0.0;
      Double disk = 0.0;
      Double gpu = 0.0;
      Double memory = 0.0;
      Double networkDownward = 0.0;
      Double networkUpward = 0.0;
      if (mockMachineState != null) {
         if (StringUtils.isNotBlank(mockMachineState.getName())) {
            name = mockMachineState.getName();
         }

         List upWardRange;
         if (StringUtils.isNotBlank(mockMachineState.getCpu())) {
            upWardRange = Arrays.asList(mockMachineState.getCpu().split(","));
            cpu = RandomUtils.nextDouble(Double.valueOf((String)upWardRange.get(0)), Double.valueOf((String)upWardRange.get(1)));
         }

         if (StringUtils.isNotBlank(mockMachineState.getDisk())) {
            upWardRange = Arrays.asList(mockMachineState.getDisk().split(","));
            disk = RandomUtils.nextDouble(Double.valueOf((String)upWardRange.get(0)), Double.valueOf((String)upWardRange.get(1)));
         }

         if (StringUtils.isNotBlank(mockMachineState.getGpu())) {
            upWardRange = Arrays.asList(mockMachineState.getGpu().split(","));
            gpu = RandomUtils.nextDouble(Double.valueOf((String)upWardRange.get(0)), Double.valueOf((String)upWardRange.get(1)));
         }

         if (StringUtils.isNotBlank(mockMachineState.getMemory())) {
            upWardRange = Arrays.asList(mockMachineState.getMemory().split(","));
            memory = RandomUtils.nextDouble(Double.valueOf((String)upWardRange.get(0)), Double.valueOf((String)upWardRange.get(1)));
         }

         if (StringUtils.isNotBlank(mockMachineState.getNetworkdownware())) {
            upWardRange = Arrays.asList(mockMachineState.getNetworkdownware().split(","));
            networkDownward = RandomUtils.nextDouble(Double.valueOf((String)upWardRange.get(0)), Double.valueOf((String)upWardRange.get(1)));
         }

         if (StringUtils.isNotBlank(mockMachineState.getNetworkupware())) {
            upWardRange = Arrays.asList(mockMachineState.getNetworkupware().split(","));
            networkUpward = RandomUtils.nextDouble(Double.valueOf((String)upWardRange.get(0)), Double.valueOf((String)upWardRange.get(1)));
         }
      }

      MachineStateVO machineStateVO = new MachineStateVO(name, cpu, disk, gpu, memory, networkDownward, networkUpward);
      return machineStateVO;
   }

   private String readFile() {
      BufferedReader reader = null;
      String laststr = "";

      try {
         InputStream fileInputStream = FileUtils.loadStreamForWonder("/mock/machinemock.json");
         Throwable var4 = null;

         try {
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);

            for(String tempString = null; (tempString = reader.readLine()) != null; laststr = laststr + tempString) {
            }

            reader.close();
         } catch (Throwable var29) {
            var4 = var29;
            throw var29;
         } finally {
            if (fileInputStream != null) {
               if (var4 != null) {
                  try {
                     fileInputStream.close();
                  } catch (Throwable var28) {
                     var4.addSuppressed(var28);
                  }
               } else {
                  fileInputStream.close();
               }
            }

         }
      } catch (IOException var31) {
         var31.printStackTrace();
      } finally {
         if (reader != null) {
            try {
               reader.close();
            } catch (IOException var27) {
               var27.printStackTrace();
            }
         }

      }

      return laststr;
   }

   private MonitorResp getMonitorData() {
      MonitorResp data = (MonitorResp)this.restAssert.getBusinessAssert(this.propertiesConfig.getMonitor().getHost(), this.propertiesConfig.getMonitor().getPort()).getData("/api/AllServerStatus", MonitorResp.class);
      if (200 == data.getResultCode()) {
         return data;
      } else {
         throw new BusinessException(data.getResultCode(), data.getResultMessage() + "失败");
      }
   }

   private MonitorResp getRulesData() {
      MonitorResp data = (MonitorResp)this.restAssert.getBusinessAssert(this.propertiesConfig.getMonitor().getHost(), this.propertiesConfig.getMonitor().getPort()).getData("/api/AllServerAlarmRule", MonitorResp.class);
      if (200 == data.getResultCode()) {
         return data;
      } else {
         throw new BusinessException(data.getResultCode(), data.getResultMessage() + "失败");
      }
   }
}
